package se.webbzon.boltzmann.item;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ItemGroup {
	
	// The singleton instance
	private static ItemGroup singleton;
	
	// A collection of all available items
	private final Map<Integer,AbstractItem> idMap;
	private final Map<String,AbstractItem> nameMap;
	
	/*============================================================
	Constructors
	============================================================*/
	
	/** Creates a new item group. **/
	private ItemGroup() {
		idMap = new HashMap<Integer,AbstractItem>();
		nameMap = new HashMap<String,AbstractItem>();
		
		initializeItems();
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	/** Returns the singleton item group instance. **/
	public static ItemGroup instance() {
		if (singleton == null)
			singleton = new ItemGroup();
		return singleton;
	}
	
	/** Returns the item associated with the given id. **/
	public AbstractItem getItem(int itemId) {
		return idMap.get(itemId);
	}
	
	/** Returns the item associated with the given name. **/
	public AbstractItem getItem(String itemName) {
		return nameMap.get(itemName.toUpperCase());
	}
	
	/** Returns an unmodifiable collection of all the items in
	 * the item group. **/
	public Collection<AbstractItem> getItems() {
		return Collections.unmodifiableCollection(idMap.values());
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Adds the given item to the item group. **/
	private void addItem(AbstractItem item) {
		AbstractItem idIt = idMap.put(item.getId(),item);
		AbstractItem nameIt = nameMap.put(item.getName().toUpperCase(),item);
		if (idIt != null)
			throw new ItemGroupCollisionException(	"Two items has the same id! " +
													"(id = " + item.getId() + 
													" for " + idIt.getName() + 
													" and " + item.getName() +")");
		else if (nameIt != null)
			throw new ItemGroupCollisionException(	"Two items has the same name! " +
													"(name = " + item.getName() +")");
	}
	
	/** Initializes the content of the item group. **/
	private void initializeItems() {
		addItem(new KeyItem("Green Orb","","orb_01"));
		addItem(new KeyItem("Red Orb","","orb_02"));
		addItem(new KeyItem("Blue Orb","","orb_03"));
	}
}
